<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="table-view">
      <template #high_form="{ form }">
        <XForm ref="form" class="w-[560px]" :fieldList="highFieldList" :options="formOption" labelPosition="top" :formData="form" :originOption="originOption"> </XForm>
      </template>

      <template #form="{ form }">
        <XForm ref="form" class="bg-[pink]" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption"> </XForm>
      </template>

      <template #toolbar_btns>
        <el-tabs v-model="activeName" class="tabs" @tab-click="tabHandleClick">
          <el-tab-pane v-for="item in tabOpt" :key="item.key" :name="item.review_status || ''">
            <template #label>
              {{ item.review_status_text }} <span>（{{ item.count || 0 }}）</span>
            </template>
          </el-tab-pane>
        </el-tabs>
        <div class="grid grid-cols-3 gap-x-2">
          <VButton type="primary" icon="Plus" @click="openEdit('add')">新增</VButton>
          <VButton type="primary" icon="Plus" @click="batchReview('batch')">审核</VButton>
          <VButton type="primary" icon="Upload" class="ml-auto" @click="openConfirmInput('add')">导 出</VButton>
        </div>
      </template>
    </VTable>
    <!-- 新增变更单 -->
    <Details ref="DetailsRef" />

    <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit" />
    <XLog ref="logRef" :api="spaChangeLog"></XLog>
  </VPage>
</template>

<script setup lang="jsx">
import { spaChangeList, spaChangeReviewStatus, spaChangeReview, spaChangeLog } from "@/api/plan"
import { ElMessage, ElMessageBox } from "element-plus"
// 新增变更单
import Details from "./components/details/index.vue"
const DetailsRef = ref()

import XForm from "@/components/XForm/index.vue"
import ConfirmInput from "@/components/ConfirmInput/index.vue"
import XLog from "@/components/XLog"

const activeName = ref("")
const tabOpt = ref([])
const tabHandleClick = (tab, event) => {
  tableRef?.value.resetAndQuery()
}
onActivated(() => {
  const { asinData } = history.state
  if (asinData) {
    addUpdateEdit(asinData)
  }
})
const router = useRouter()
const addUpdateEdit = (data) => {
  let form = JSON.parse(data)
  let params = { type: "add", title: "新增", form }
  DetailsRef.value.open(params)
}
//获取下拉数据
onMounted(() => {
  const { asinData } = history.state
  if (asinData) {
    addUpdateEdit(asinData)
  }
  // let params = {
  //   type: "add",
  //   title: "新增",
  // }
  // DetailsRef.value.open(params)
  getOption()
})
import { enumGet, enumOptions } from "@/api"
import { getCountry, getSupplie } from "@/api"
const getOption = async () => {
  let keys = [...fieldList.value, ...highFieldList.value].filter((v) => v.originField)

  let enumParams = keys.filter((v) => v.enumOriginField).map((v) => v.originField)
  const enumData = (await enumOptions({ params: enumParams }))?.data

  let enumGetName = keys.filter((v) => !v.enumOriginField).map((v) => v.originField)
  enumGetName = [...enumGetName]
  const { data } = await enumGet({ name: [...enumGetName, "Plan.PlanSpaChange.ReviewStatusEnum"] })
  let optData = { ...enumData, ...data }
  for (const key in optData) {
    originOption.value[key] = optData[key]
  }

  originOption.value.country = (await getCountry()).data
  originOption.value.supplier = (await getSupplie())?.data

  console.log(originOption.value)
}
// 枚举 数据
const originOption = ref({
  "Plan.PlanSpaChange.ReviewStatusEnum": [],

  review_type: {
    1: [
      { label: "计划审核通过", value: "PLAN_PASS" },
      { label: "计划审核不通过", value: "PLAN_REJECT" },
    ],
    2: [
      { label: "采购审核通过", value: "PURCHASE_PASS" },
      { label: "采购审核不通过", value: "PURCHASE_REJECT" },
    ],
    3: [
      { label: "采购经理审核通过", value: "PURCHASE_MANAGER_PASS" },
      { label: "采购经理审核不通过", value: "PURCHASE_MANAGER_REJECT" },
    ],
  },
})
// 打开编辑弹窗
const openEdit = (type, row = {}) => {
  let params = {}
  if (type == "add") {
    params = { type: "add", title: "新增" }
  }
  if (type == "edit") {
    params = { type: "edit", title: "编辑", id: row.id }
  }
  DetailsRef.value.open(params)
}

const tableRef = ref()
const logRef = ref()
const data = reactive({
  title: "详情",
  formData: {},
  loading: false,

  batchVisible: false,
  currentConfirm: {},
})
const { title, formData, loading, batchVisible, currentConfirm } = toRefs(data)

// 批量 审核
const batchReview = (type, row = {}) => {
  let params = {}
  if (type == "one") {
    params = {
      id: [row.id],
      review_status: row.review_status,
    }
  } else {
    let arr = getSelectRow()
    let review_status = [...new Set(arr.map((v) => v.review_status))]
    if (review_status.length > 1) {
      ElMessage({ showClose: true, message: "只能操作同一状态数据", type: "warning" })
      return false
    }
    params = {
      id: arr.map((v) => v.id),
      review_status: review_status[0],
    }
  }
  openConfirmInput("review", params)
}
// 保存 弹窗 表单编辑
const handleConfirmSubmit = (param) => {
  console.log(param)
  let requests = null
  switch (currentConfirm.value.type) {
    case "review": // 审核
      requests = spaChangeReview
      break
  }
  // console.log(currentConfirm.value)
  requests(param).then((res) => {
    ElMessage.success(res.message)
    batchVisible.value = false
    query()
    nextTick(() => {
      currentConfirm.value = {}
    })
  })
}

// 开启 弹窗 表单编辑
const openConfirmInput = (type, params) => {
  let confirm = {}
  switch (type) {
    case "review": // 审核
      confirm = currentConfirmOpt.review
      confirm.fieldOptions[0].options.data = originOption.value.review_type[params.review_status]
      confirm.form = {
        id: params.id,
      }
      break
  }

  confirm.type = type
  currentConfirm.value = confirm
  batchVisible.value = true
}
const currentConfirmOpt = {
  review: {
    title: "审核",
    // formOptions: { labelPosition: "right", labelWidth: "140px" },
    fieldOptions: [
      {
        field: "review_type",
        label: "审核状态",
        type: "radio",
        options: {
          data: [],
        },
        style: { width: "300px" },
      },
      {
        field: "remark",
        label: "备注信息",
        type: "textarea",
        style: { width: "320px" },
        autosize: { minRows: 4, maxRows: 6 },
      },
    ],
    rules: {
      sssss: [{ required: true, message: "请选择", trigger: "change" }],
    },
    tips: "可针对“待计划审核、待运营审核”状态的SKU操作",
  },
}

// 获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  return getCheckboxRecords
}

// //启用
// const handleStatus = (status) => {
//   const arr = getSelectRow()
//   if (!arr.length) {
//     return false
//   }

//   ElMessageBox.confirm(`此操作将 ${status ? "启用" : "禁用"} ${arr.length}条数据, 是否继续?`, "提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//     confirmButtonClass: "oms-message-confirm-button",
//   }).then(async () => {
//     try {
//       // deleteSetting({ id }).then(res => {
//       ElMessage.success("操作成功")
//       query()
//       // })
//     } catch (e) {
//       throw Error(e)
//     }
//   })
// }
// // 查询
const query = () => {
  tableRef?.value.query()
}

const formOption = ref({ inline: true })

const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  // { slot: "monthrange", style: { width: "200px" } },

  {
    field: "orderRange",
    placeholder: "可批量搜索",
    select: [
      { label: "计划变更单", value: "change_number" },
      { label: "备货计划单", value: "pr_number" },
    ],
    selectStyle: { width: "120px" },
    ...publicStyle,
  },
  {
    field: "skuRange",
    placeholder: "可批量搜索",
    select: [
      { label: "SKU", value: "sku" },
      { label: "自定义SKU", value: "custom_sku" },
      { label: "ASIN", value: "asin" },
    ],
    ...publicStyle,
  },

  {
    field: "change_reason",
    type: "select",
    originField: "Plan.PlanSpaChange.ChangeReasonEnum",
    options: {
      placeholder: "变更原因",
    },
    ...publicStyle,
  },
  {
    field: "shipTimeRange",
    type: "dateTimeRangeNorm",
    select: [
      { label: "变更后预计到货时间", value: "before_ship_time" },
      { label: "变更前预计到货时间", value: "after_ship_time" },
    ],
    selectStyle: { width: "170px" },
    style: { width: "350px" },
  },

  {
    field: "timeRange",
    type: "dateTimeRangeNorm",
    select: [
      { label: "添加时间", value: "created_at" },
      { label: "审核时间", value: "reviewed_at" },
    ],
    selectStyle: { width: "100px" },
    style: { width: "350px" },
  },
])

const highFieldList = ref([
  {
    label: "计划类型",
    field: "plan_type",
    type: "select",
    placeholder: "计划类型",
    originField: "Plan.PlanStockingPlan.TypeEnum",
    options: {
      placeholder: "计划类型",
    },
    style: { width: "120px" },
  },
  {
    label: "国家",
    field: "site_code",
    type: "select",
    originField: "country",
    enumOriginField: true, // 获取枚举接口不同
    options: {
      placeholder: "国家",
    },
    style: { width: "200px" },
  },
  {
    label: "商品活跃度",
    field: "active_status",
    type: "select",
    originField: "goods_active",
    enumOriginField: true, // 获取枚举接口不同
    options: {
      placeholder: "商品活跃度",
    },
    style: { width: "120px" },
  },
  {
    label: "商品状态",
    field: "sales_status",
    type: "select",
    originField: "sku_status",
    enumOriginField: true, // 获取枚举接口不同
    options: {
      placeholder: "商品状态",
    },
    style: { width: "120px" },
  },
  {
    label: "货源状态",
    field: "supply_status",
    type: "select",
    originField: "sku_resource_status",
    enumOriginField: true, // 获取枚举接口不同
    options: {
      placeholder: "货源状态",
    },
    style: { width: "120px" },
  },

  {
    label: "供应商",
    field: "supplier_id",
    type: "selectV2",
    placeholder: "供应商",
    originField: "supplier",
    enumOriginField: true, // 获取枚举接口不同
    itemProps: {
      multiple: true,
      collapseTags: true,
      props: {
        label: "supplier_name",
        value: "s_id",
      },
    },
    style: { width: "200px" },
  },
  {
    field: "userRange",
    label: "计划人员",
    type: "cascader",
    placeholder: "计划人员",
    select: [
      { label: "计划人员", value: "planner_user" },
      { label: "运营人员", value: "operator_user" },
      { label: "采购人员", value: "purchaser_user" },
    ],
    multiple: true,
    collapseTags: true,
    itemStyle: { width: "100%" },
    style: { width: "270px", zIndex: 99999 },
  },

  {
    field: "create_user",
    label: "添加人员",
    type: "cascader",
    placeholder: "添加人员",
    select: [
      { label: "添加人员", value: "timeData" },
      { label: "审核人员", value: "custom_sku" },
    ],
    multiple: true,
    collapseTags: true,
    // itemStyle: { width: '100%' },
    style: { width: "270px", zIndex: 99999 },
  },
])

const salesTagColor = {
  待计划总监审核: "bg-[#F2EAFF] text-[#8134FF]",
  审核完成: "bg-[#E6E7E9] text-[#333]",
  已驳回: "bg-[#FCE5E7] text-[#E50113]",
}

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      orderRange: { type: "change_number", value: "" },
      skuRange: { type: "sku", value: "" },
      shipTimeRange: { type: "before_ship_time", value: "" },
      timeRange: { type: "created_at", value: "" },
      userRange: { type: "planner_user", value: "" },

      create_user: { type: "skuData", value: "" },
    },
  },
  // cellStyle: rowStyle,
  // showOverflow: false,
  // rowConfig: { height: "auto" },
  rowConfig: { height: "160" },
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },
    {
      title: "变更单信息",
      width: 200,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <div class={`status-tag dark mr-[2px] ${salesTagColor[row.review_status_text] || "bg-[#EAF3FF] text-[#3487FF]"}`}>{row.review_status_text}</div>
              <div class="text-blue">
                <VText value={row.change_number} />
              </div>
            </div>
            <VText title="变更类型" value={row.change_type_text} line={1} />
          </div>
        ),
      },
    },

    {
      title: "计划单信息",
      width: 220,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <div>
                <VText value={row.stocking_plan?.plan_type_text} line={1} />
              </div>
              <el-divider direction="vertical" />
              <VText value={row.xxx} class="text-blue" /> x
            </div>
            <VText title="备货类型" value={row.xxx} line={1} />
            <VText title="计划部门" value={row.stocking_plan?.department_name} line={1} />
          </div>
        ),
      },
    },

    {
      title: "变更商品",
      width: 220,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <div>
                <VText value={row.spa?.review_status_text} line={1} />
              </div>
              <el-divider direction="vertical" />
              <VText value={row.spa.sku} class="text-blue" />
            </div>

            <VText title="自定义" value={row.spa.custom_sku} line={1} />
            <VText title="ASIN" value={row.spa.asin} line={1} />

            <div class="grid grid-cols-2">
              <VText title="国家" value={row.spa.site_code} line={1} />
              <VText title="活跃度" value={row.spa.activity_status_text} line={1} class={row.spa.activity_status_text == "新品" ? "text-green" : ""} />
            </div>
          </div>
        ),
      },
    },
    {
      title: "变更数量",
      width: 100,
      slots: {
        default: ({ row }) => (
          <div>
            <div>{row.before_stocking_quantity}</div>
            <svg-icon icon-class="arrow_more_down" class="text-[#FAAD14]" />
            <div>{row.after_stocking_quantity}</div>
          </div>
        ),
      },
    },
    {
      title: "预计发货时间",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <div>{row.before_ship_time}</div>

            <svg-icon icon-class="arrow_more_down" class="text-[#FAAD14]" />

            <div>{row.after_ship_time}</div>
          </div>
        ),
      },
    },
    {
      title: "变更原因",
      width: 180,
      field: "change_reason_text",
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.change_type_text} line={1} />
            <VText value={row.change_reason_text} line={1} />
          </div>
        ),
      },
    },
    {
      title: "采购信息",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <VText title="采购价" value={row.spa_purchases?.purchase_price} line={1} />
              <el-divider direction="vertical" />
              {row.spa_purchases?.min_order_quantity}起批
            </div>

            <VText title="采购天数" value={row.spa_purchases?.purchase_days} line={1} />
            <VText title="单箱数量" value={row.spa_purchases?.mpq_min_quantity} line={1} />
            <VText title="供应商" value={row.spa_purchases?.supplier_name} line={1} />
          </div>
        ),
      },
    },

    {
      title: "变更前采购单信息",
      width: 140,
      slots: {
        default: ({ row }) =>
          row.before_purchase_info?.po_number ? (
            <div>
              <VText title="采购单" value={row.before_purchase_info?.po_number} line={1} type="link" />
              <VText title="采购数量" value={row.before_purchase_info?.purchase_quantity} line={1} />
              <VText title="状态" value={row.before_purchase_info?.purchase_status} line={1} />
            </div>
          ) : (
            <div>未采购</div>
          ),
      },
    },
    {
      title: "变更前备库单信息",
      width: 140,

      slots: {
        default: ({ row }) =>
          row.before_stock_info?.stock_number ? (
            <div>
              <VText title="备库单" value={row.before_stock_info?.stock_number} line={1} type="link" />
              <VText title="发货数量" value={row.before_stock_info?.shipped_quantity} line={1} />
              <VText title="状态" value={row.before_stock_info?.status} line={1} />
            </div>
          ) : (
            <div>未建单</div>
          ),
      },
    },

    {
      title: "审核备注",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="计划审核" value={row.plan_review_remark} line={1} />
            <VText title="采购审核" value={row.purchase_review_remark} line={1} />
            <VText title="经理审核" value={row.manager_review_remark} line={1} />
          </div>
        ),
      },
    },

    {
      title: "人员信息",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="计划" value={row.spa?.planner_user_text} line={1} />
            <VText title="运营" value={row.spa?.operator_user_text} line={1} />
            <VText title="采购" value={row.spa?.purchaser_user_text} line={1} />
            <VText title="添加" value={row.spa?.created_by_text} line={1} />
            <VText title="计划审核" value={row.plan_approver_by} line={1} />
            <VText title="采购审核" value={row.purchase_reviewer_by} line={1} />
            <VText title="经理审核" value={row.manager_reviewer_by} line={1} />
          </div>
        ),
      },
    },
    {
      title: "时间信息",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="计划审核" value={row.plan_review_time} line={1} />
            <VText title="采购审核" value={row.purchase_review_time} line={1} />
            <VText title="经理审核" value={row.manager_review_time} line={1} />
          </div>
        ),
      },
    },

    {
      title: "操作",
      width: 150,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => openEdit("edit", row)}>
                编辑
              </el-button>

              <el-button link type="primary" onClick={() => batchReview("one", row)}>
                审核
              </el-button>
              <el-button link type="primary" onClick={() => logRef?.value.open({ id: row.id })}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          ...form,
          page: page.pageNum,
          page_num: page.pageSize,
        }
        console.log(199887)
        console.log(params)
        spaChangeReviewStatus(params).then((res) => {
          console.log(res)
          tabOpt.value = res.data
        })
        return spaChangeList({ ...params, review_status: activeName.value })
      },
    },
  },
})
</script>
<style lang="scss" scoped>
.table-view {
  background: #efefef;
  :deep(.vxe-cell) {
    max-height: 100% !important;
  }
  :deep(.status-tag) {
    height: 14px;
    line-height: 14px;
    padding: 0 3px;
    text-align: center;
    border-radius: 2px;
    font-size: 10px;
  }
}
:deep(.vx-table__form) {
  .vx-table__form-content {
    border-radius: 8px;
    margin-bottom: 8px;
    background-image: none;
  }
}
:deep(.vx-table__content) {
  background: #fff;
  border-radius: 8px 8px 0 0;
}

:deep(.row-item) {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 4px;
  margin-bottom: 2px;
}

:deep(.tabs) {
  margin-top: 0 !important;
  overflow: hidden;
  width: 100%;
  .el-tabs__header {
    margin-bottom: 0;
    height: 28px;
    line-height: 28px;
    .el-tabs__nav {
      border-radius: 4px !important;
      overflow: hidden;
    }
  }
  .el-tabs__item {
    height: 28px;
    line-height: 28px;
  }
}
</style>
